package View;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import Command.Command;
import Command.Delete;
import Command.Insert;
import Command.Select;
import Command.Update;

public class CommanderServer extends Thread{
	private Socket _server;
	private boolean isClose = false;
	
	public CommanderServer(Socket server) throws IOException
	{
		this._server = server;
		start();
			
	}
	public void run()
	{
		try{	
			//this.server = new ServerSocket(3008);
			//Socket	_server = this.server.accept();
			InputStream is = _server.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			
			OutputStream os = _server.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			
			do{			
				
			int nSql;
			Vector<String> commands = new Vector<String>();
			//receive nCommands
			nSql = ois.readInt();
			System.out.println("The number of queries: " + nSql);
			for(int i= 0 ; i < nSql; i++)
			{
				String cmd = ois.readUTF();
				commands.add(cmd);
			}
			
			//execute sql
			Vector<Object> result = new Vector<Object>();
			String str ="";
			Object obj = null;
			for(int i = 0; i < nSql; i++)
			{
				str = commands.get(i);
				if(Command.isDelete(str)){
					Delete del = new Delete(str);
					obj= del.executeQuery();
				}
				else if(Command.isInsert(str))
				{
					Insert insert = new Insert(str);
					obj = insert.executeQuery();
				}
				else if(Command.isUpdate(str))
				{
					Update update = new Update(str);
					obj = update.executeQuery();
				}
				else if(Command.isSelect(str))
				{
					Select sel = new Select(str);
					obj = sel.executeQuery();
				}
				else obj = "Failed! We can't execute this command. Please check and try again.";
			
				result.add(obj);
			}
			
			int nResult = result.size();
			//send nResult
			oos.writeInt(nResult);
			oos.flush();
			System.out.println("Sending the number of results : " + nResult);
			//send result
			
			for(int i = 0; i < nResult; i++)
			{
				if(result.get(i) == null)
					oos.writeObject("failed");
				else 
					oos.writeObject(result.get(i));				
				
				oos.flush();				
			}	
			
		}while(!isClose);	

		ois.close();
		oos.close();
			
		}
		catch(Exception ex)
		{
			//ex.printStackTrace();			
			JPanel panel = null;							
			JOptionPane.showMessageDialog(panel, "Server exception : " + ex.getMessage(), 
				    "Error", JOptionPane.ERROR_MESSAGE);
		}
	}
}
